//
//  NewHomeTopChooseView.m
//  GC_OC
//
//  Created by  Quan He on 2022/4/9.
//

#import "NewHomeTopChooseView.h"
#import "AudioViewController.h"
#import "NewHomeViewController.h"

@interface NewHomeTopChooseView()
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *hideButton;
@property (nonatomic, strong) HomeChooseButton *currentButton;
@property (nonatomic, strong) HomeChooseButton *allCurrentButton;
@property (nonatomic, strong) UIView *allView;
@property (nonatomic, strong) UIView *allBackView;
@property (nonatomic, assign) CGFloat maxHeight;
@property (nonatomic, strong) CAShapeLayer *cornerLayer;
@property (nonatomic, assign) BOOL vcIsShow;
@property (nonatomic, assign) NSInteger maxLine;
@end

@implementation NewHomeTopChooseView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initUI];
        self.maxLine = 0;
    }
    return self;
}

- (void)initUI {
    self.scrollView = [[HQScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width - 45, self.height)];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self addSubview:self.scrollView];
    self.backgroundColor = [UIColor colorWithRed:0.96 green:0.97 blue:0.98 alpha:1.00];
    CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotateAnimation.fromValue = [NSNumber numberWithFloat:0];
    rotateAnimation.toValue = [NSNumber numberWithFloat:-0.5*M_PI];
    rotateAnimation.duration = 0.3;
    rotateAnimation.removedOnCompletion = NO;
    rotateAnimation.fillMode = kCAFillModeForwards;
    rotateAnimation.repeatCount = 1;
    [self.hideButton.layer addAnimation:rotateAnimation forKey:@"animation0"];
}

- (void)setSuperView:(UIView *)view {
    UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
    
    [window addSubview:self.allBackView];
    [window addSubview:self.allView];
    [window addSubview:self.hideButton];
}

- (void)setInfoArr:(NSArray *)infoArr {
    _infoArr = infoArr;
    [self addButton];
    [self addAllButton];
}

- (void)shouldHide:(BOOL)hide {
    _vcIsShow = !hide;
    if (hide) {
        [self hideAllView];
    }
    if (self.infoArr.count != 0 && self.maxLine != 0) {
        self.hideButton.hidden = hide;
    }
}

- (void)addButton {
    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    HomeChooseButton *lastButton;
    for (int i = 0; i<self.infoArr.count; i++) {
        HomeChooseButton *btn = [[HomeChooseButton alloc] initButtonWithTitle:self.infoArr[i][@"label"]];
        [btn addTarget:self action:@selector(btnTouchUpClick:) forControlEvents:(UIControlEventTouchUpInside)];
        btn.tag = 500+i;
        [self.scrollView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.scrollView);
            make.height.equalTo(@(30));
            if (i == 0) {
                make.left.equalTo(self.scrollView).offset(10);
                btn.isChoose = YES;
                self.currentButton = btn;
            }else{
                make.left.equalTo(lastButton.mas_right);
            }
        }];
        lastButton = btn;
    }
    [self layoutIfNeeded];
    self.scrollView.contentSize = CGSizeMake(lastButton.frame.origin.x + lastButton.frame.size.width, self.height);
    BOOL isHide = self.scrollView.contentSize.width < SCREEN_WIDTH;
    if (self.vcIsShow) {
        self.hideButton.hidden = isHide;
    }
    if (isHide) {
        self.scrollView.frame = CGRectMake(0, 0, self.frame.size.width, self.height);
    }else {
        self.scrollView.frame = CGRectMake(0, 0, self.frame.size.width - 45, self.height);
    }
}

- (void)addAllButton {
    [self.allView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    HomeChooseButton *lastButton;
    UIFont *font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
    CGFloat heightSpace = (self.height - 30) * 0.5;
    self.maxLine = 0;
    int lastX = 10;
    for (int i = 0; i<self.infoArr.count; i++) {
        NSString *title = self.infoArr[i][@"label"];
        HomeChooseButton *btn = [[HomeChooseButton alloc] initButtonWithTitle:title];
        CGFloat width = [GC_OCTool getWidthForLabel:title andFont:font andHeight:30] + 30;
        CGFloat maxWidth = (SCREEN_WIDTH - 65);
        if (self.maxLine != 0) {
            maxWidth = SCREEN_WIDTH - 20;
        }
        if ((width + lastX) > maxWidth) {//需要换行
            self.maxLine += 1;
            lastX = 10;
        }
        
        btn.frame = CGRectMake(lastX, heightSpace + self.maxLine * self.height, width, 30);
        
        [btn addTarget:self action:@selector(allBtnTouchUpClick:) forControlEvents:(UIControlEventTouchUpInside)];
        btn.tag = 600 + i;
        [self.allView addSubview:btn];
        if ([self.currentButton.titleLabel.text isEqualToString:self.infoArr[i][@"label"]]) {
            btn.isChoose = YES;
            self.allCurrentButton = btn;
        }
        lastButton = btn;
        lastX += width;
    }
    self.maxHeight = lastButton.frame.origin.y + heightSpace + 30 + 15;
}

- (void)allBtnTouchUpClick:(HomeChooseButton *)sender
{
    self.allCurrentButton.isChoose = NO;
    sender.isChoose = YES;
    self.allCurrentButton = sender;
    
    self.currentButton.isChoose = NO;
    self.currentButton = [self.scrollView viewWithTag:sender.tag - 100];
    self.currentButton.isChoose = YES;
    
    AudioViewController* homeOne=[[AudioViewController alloc]init];
    homeOne.hidesBottomBarWhenPushed = YES;
    homeOne.idString = self.classId;
    homeOne.title = self.infoArr[sender.tag-600][@"label"];
    homeOne.tagString = self.infoArr[sender.tag-600][@"id"];
    UIViewController *controler = [UIViewController currentViewController];
    if ([controler.class isKindOfClass:NSClassFromString(@"NewHomeViewController")]) {
        homeOne.parentName = ((NewHomeViewController *)controler).titleString;
    }else {
        homeOne.parentName = controler.title;
    }
    [controler.navigationController pushViewController:homeOne animated:YES];
    
    [self hideAllView];
    CGFloat x = self.currentButton.frame.origin.x - 0.5 * self.scrollView.frame.size.width;
    [self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
}

- (void)btnTouchUpClick:(HomeChooseButton *)sender
{
    self.currentButton.isChoose = NO;
    sender.isChoose = YES;
    self.currentButton = sender;
    self.allCurrentButton.isChoose = NO;
    self.allCurrentButton = [self.allView viewWithTag:sender.tag + 100];
    self.allCurrentButton.isChoose = YES;
    AudioViewController* homeOne=[[AudioViewController alloc]init];
    homeOne.hidesBottomBarWhenPushed = YES;
    homeOne.idString = self.classId;
    homeOne.title = self.infoArr[sender.tag-500][@"label"];
    homeOne.tagString = self.infoArr[sender.tag-500][@"id"];
    UIViewController *controler = [UIViewController currentViewController];
    if ([controler.class isKindOfClass:NSClassFromString(@"NewHomeViewController")]) {
        homeOne.parentName = ((NewHomeViewController *)controler).titleString;
    }else {
        homeOne.parentName = controler.title;
    }
    [controler.navigationController pushViewController:homeOne animated:YES];

    CGFloat x = self.currentButton.frame.origin.x - 0.5 * self.scrollView.frame.size.width;
    [self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];

}

- (void)showAllView {
    if (self.allBackView.isHidden == NO) {
        [self hideAllView];
        return;
    }
    [self.allView.superview bringSubviewToFront:self.allView];
    [self.allView.superview bringSubviewToFront:self.hideButton];
    self.allBackView.hidden = NO;
    self.allView.hidden = NO;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, SCREEN_WIDTH, self.maxHeight) byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(16, 16)];
    self.cornerLayer.path = path.CGPath;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.allBackView.alpha = 1;
        self.allView.frame = CGRectMake(0, self.allView.frame.origin.y, SCREEN_WIDTH, self.maxHeight);
    } completion:^(BOOL finished) {
        
    }];
    
    CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotateAnimation.fromValue = [NSNumber numberWithFloat:-0.5*M_PI];
    rotateAnimation.toValue = [NSNumber numberWithFloat:0];
    rotateAnimation.duration = 0.3;
    rotateAnimation.removedOnCompletion = NO;
    rotateAnimation.fillMode = kCAFillModeForwards;
    rotateAnimation.repeatCount = 1;
    [self.hideButton.layer addAnimation:rotateAnimation forKey:@"animation0"];
}

- (void)hideAllView {
    CABasicAnimation *rotateAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotateAnimation.fromValue = [NSNumber numberWithFloat:0];
    rotateAnimation.toValue = [NSNumber numberWithFloat:-0.5*M_PI];
    rotateAnimation.duration = 0.3;
    rotateAnimation.removedOnCompletion = NO;
    rotateAnimation.fillMode = kCAFillModeForwards;
    rotateAnimation.repeatCount = 1;
    [self.hideButton.layer addAnimation:rotateAnimation forKey:@"animation0"];

    [UIView animateWithDuration:0.3 animations:^{
        self.allBackView.alpha = 0;
        self.allView.frame = CGRectMake(0, self.allView.frame.origin.y, SCREEN_WIDTH, 0);
    } completion:^(BOOL finished) {
        self.allBackView.hidden = YES;
        self.allView.hidden = YES;

    }];
}
#pragma mark - Lazyload
- (UIButton *)hideButton {
    if (!_hideButton) {
        _hideButton = ({
            CGFloat y = self.frame.origin.y;
            if (y == 0) {
                y = topHeight;
            }
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.adjustsImageWhenHighlighted = NO;
            [button setImage:[UIImage imageNamed:@"xiangxia"] forState:UIControlStateNormal];
            button.hitTestEdgeInsets = UIEdgeInsetsMake(-12, -12, -12, -12);
            [button addTarget:self action:@selector(showAllView) forControlEvents:UIControlEventTouchUpInside];
            button.frame = CGRectMake(SCREEN_WIDTH - 30, y + 0.5*(self.height - 15), 15, 15);
            button.hidden = YES;
            button;
        });
    }
    return _hideButton;
}

- (UIView *)allBackView {
    if (!_allBackView) {
        CGFloat y = self.frame.origin.y;
        if (y == 0) {
            y = topHeight;
        }
        _allBackView = [[UIView alloc] initWithFrame:CGRectMake(0, y, SCREEN_WIDTH, SCREEN_HEIGHT - self.frame.origin.y)];
        _allBackView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.2f];
        _allBackView.hidden = YES;
        _allBackView.alpha = 0;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAllView)];
        [_allBackView addGestureRecognizer:tap];
    }
    return _allBackView;
}

- (UIView*)allView
{
    if(!_allView) {
        CGFloat y = self.frame.origin.y;
        if (y == 0) {
            y = topHeight;
        }
        _allView = [[UIView alloc] initWithFrame:CGRectMake(0, y, SCREEN_WIDTH, 0)];
        _allView.backgroundColor = [UIColor colorWithRed:0.96 green:0.97 blue:0.98 alpha:1.00];
        _allView.hidden = YES;
        _allView.clipsToBounds = YES;
        _allView.layer.mask = self.cornerLayer;
    }
    return _allView;
}

- (CAShapeLayer *)cornerLayer {
    if (!_cornerLayer) {
        _cornerLayer = [CAShapeLayer layer];
    }
    return _cornerLayer;
}
@end

@implementation HomeChooseButton
- (instancetype)initButtonWithTitle:(NSString *)title {
    self = [super initWithFrame:CGRectMake(0, 0, 0, 0)];
    if (self) {
        
        [self setTitle:title forState:UIControlStateNormal];
        self.isChoose = NO;
        self.layer.masksToBounds = YES;
        self.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        self.layer.cornerRadius = 15;
        
        self.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
        [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        [self setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithRed:0.84 green:0.93 blue:0.98 alpha:1.00]] forState:UIControlStateHighlighted];
        [self setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor colorWithRed:0.49 green:0.49 blue:0.52 alpha:1.00] forState:UIControlStateNormal];
    }
    return self;
}

- (void)setIsChoose:(BOOL)isChoose {
    _isChoose = isChoose;
//    if (isChoose) {
//        self.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightMedium];
//        [self setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
//        [self setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithRed:0.84 green:0.93 blue:0.98 alpha:1.00]] forState:UIControlStateHighlighted];
//    }else {
//        self.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightLight];
//        self.backgroundColor = [UIColor clearColor];
//        [self setTitleColor:[UIColor colorWithRed:0.49 green:0.49 blue:0.52 alpha:1.00] forState:UIControlStateNormal];
//    }
}

@end
